package io.wen.bd.s3m3.zookeeper;

import org.I0Itec.zkclient.ZkClient;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DynamicConfigApplication {
    private static final String ZK_CONFIG_PATH = "/dynamic_config";
    private static final String quorums = "hadoop01:2181,hadoop02:2181,hadoop03:2181";
    private static final String HIVE_CONFIG = "{\"url\":\"jdbc:mysql://hadoop03:3306/hivemetadata\",\"driverClassName\":\"com.mysql.jdbc.Driver\",\"username\":\"hive\",\"password\":\"Ven3.06+\"}";
    private static final String AZKABAN_CONFIG = "{\"url\":\"jdbc:mysql://hadoop03:3306/azkaban\",\"driverClassName\":\"com.mysql.jdbc.Driver\",\"username\":\"azkaban\",\"password\":\"Ven3.06+\"}";

    public static void main(String[] args) throws SQLException, InterruptedException {
        final ZkClient zkClient = new ZkClient(quorums);
        if (!zkClient.exists(ZK_CONFIG_PATH)) {
            System.out.println("create zookeeper path: " + ZK_CONFIG_PATH);
            zkClient.createPersistent(ZK_CONFIG_PATH, HIVE_CONFIG);
        }
        final DynamicDataSource dataSource = new DynamicDataSource(quorums, ZK_CONFIG_PATH);
        System.out.println("try first connect ...");
        connect(dataSource);

        // 更新配置信息
        zkClient.writeData(ZK_CONFIG_PATH, AZKABAN_CONFIG);
        // 等待watcher部分更新配置完成
        Thread.sleep(1000);
        System.out.println("config updated.");

        System.out.println("try second connect ...");
        connect(dataSource);
    }

    /**
     * 连接到数据库，获取当前配置、用户信息
     */
    private static void connect(DynamicDataSource dataSource) throws SQLException {
        System.out.println("current config: " + dataSource.getConfigMap());
        final Connection connection = dataSource.getConnection();
        final ResultSet resultSet = connection.prepareStatement("select current_user()").executeQuery();
        while (resultSet.next()) {
            final String currentUesr = resultSet.getString(1);
            System.out.println("current user: " + currentUesr);
        }
    }
}


